(function() {
    angular
        .module('ydApp.login', [])
        .config(function($stateProvider) {
            $stateProvider.state('login', {
                url: '/login',
                cache: false,
                controller: "loginCtrl",
                templateUrl: 'views/login/login.html'
            });
            $stateProvider.state('loading', {
                url: '/loading',
                controller: "loadingCtrl",
                templateUrl: 'views/login/loading.html'
            });
        })
        .controller("loginCtrl", loginCtrl)
        .controller("loadingCtrl", loadingCtrl);


    function loginCtrl($scope, $state, xhr, localStore, popup, $ionicLoading) {
        var vm = $scope.vm = {};
        vm.user = {};

        vm.toHome = function() {
            $state.go('tabs.home')
        }

        vm.init = function() {
            var loginInfo = localStore.get("loginInfo");
            if (!angular.isUndefined(loginInfo) && loginInfo != null) {
                vm.user.code = loginInfo.code;
                vm.user.password = loginInfo.password;
                vm.remember = true;
            }
        }

        vm.init();

        vm.login = function() {
            $ionicLoading.show({
                template: '正在登陆'
            });
            if (vm.remember) {
                localStore.save("loginInfo", {
                    code: vm.user.code,
                    password: vm.user.password
                })
            } else {
                localStore.del("loginInfo");
            }
            xhr.get('HealthInquiry/com/login/app', vm.user).then(function(result) {
                var code=vm.user.code;
                var userInfoUrl = result.data.userType == 1 ? "HealthInquiry/com/user/findById" : "HealthInquiry/com/doctor/findById";
                xhr.get(userInfoUrl, {id:result.data.id}).then(function(data) {
                    vm.user=data.data;
                    vm.user.code=code;
                    vm.user.userType=result.data.userType;
                    console.log(vm.user)
                    localStore.save('user', vm.user);
                    localStore.save('userType', vm.user.userType);
                    $state.go('tabs.home');
                });
            });
        }


        vm.go = function(router) {
            $state.go(router);
        }
    }

    function loadingCtrl($scope, localStore, $state) {
        $scope.toHome = function() {
            localStore.save('isStart', true);
            $state.go('tabs.home')
        }
    }
})();
